import os
import time

from Extend.GrandClass import GrandClass
from Extend.Log import LogMethod
from Extend.SqlHelper import SqlServer
from Extend.NoSql import SharedData
from Extend.NoSql import Heart, Distribution


class Logs(GrandClass):

    def __init__(self, server_info: dict):
        super().__init__()
        server = server_info['Server']
        user = server_info['User']
        password = server_info['Password']
        db = server_info['DataBase']
        self.db = SqlServer(server, user, password, db)

    def addServer(self, server_list: list):
        pass

    # 循环主逻辑
    def startMonitors(self):
        while Heart.getMeHeart(self.__class__.__name__, ):
            super().startMonitors()
            try:
                if int(SharedData.GetLogLen()) > 0:
                    self.insertLog(SharedData.GetLog())
                if int(Distribution.GetLogLen()) > 0:
                    self.insertDistributor(Distribution.getLog())
            except Exception as err:
                LogMethod.addLog([90, "日志写入数据库失败！", str(err)])
                Heart.setMeStat(self.__class__.__name__, False)
                Heart.setMeHeart(self.__class__.__name__, False)
                return
            time.sleep(1)
        Heart.setMeStat(self.__class__.__name__, False)

    def insertLog(self, logs: dict):
        for x, y in logs.items():
            if type(y) is str:
                logs[x] = y.replace("'", '"')
        sql = "INSERT INTO [logs]([type_id], [log_info], [log_details], [occurrence_time], [log_type]) " \
              "VALUES ({type_id}, N'{log_info}',N'{log_details}','{occurrence_time}', N'{log_type}')".format(**logs)
        self.db.addData(sql)

    def insertDistributor(self, logo: dict):
        field = ""
        value = ""
        for x, y in logo.items():
            field += "[%s]," % x
            value += "'%s'," % y
        sql = "INSERT INTO distributionLog({}) values({})".format(field.rstrip(','), value.rstrip(','))
        self.db.addData(sql)


if __name__ == "__main__":
    log = Logs({"Server": "172.16.200.251", "User": "sa", "Password": "2020", "DataBase": "DataDistribution"})
    log.start()
